package com.sca.dealf.sentinelhandle;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.degrade.circuitbreaker.CircuitBreakerStrategy;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.alibaba.nacos.common.http.param.MediaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sca.dealf.entity.CommonResult;
import com.sca.dealf.entity.Product;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class CustomerBlockExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {

        CommonResult<Product> result = null;
        if(e instanceof FlowException) {
            result = new CommonResult<Product>(101,"自定义限流处理",null);
        }
        if(e instanceof DegradeException) {
            result = new CommonResult<Product>(102,"自定义降级",null);
        }
        if(e instanceof ParamFlowException) {
            result = new CommonResult<Product>(102,"自定义热点参数限流",null);
        }
        if(e instanceof SystemBlockException) {
            result = new CommonResult<Product>(102,"自定义触发系统保护",null);
        }
        response.setStatus(500);
        response.setCharacterEncoding("utf-8");
        response.setContentType(MediaType.APPLICATION_JSON);
        new ObjectMapper().writeValue(response.getWriter(), result);


    }
}
